package com.yunsc.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 自定义元对象字段填充
 * @date: 2024-04-14 13:33
 */
@Slf4j
@Component
public class MyMetaObjectHandler  implements MetaObjectHandler {
    /**
     * 插入元对象字段填充
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 新增时自动填充 create_time, update_time 字段
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.getOriginalObject().toString());
        // metaObject.setValue("createTime",new Date());
        metaObject.setValue("createTime", (int) (System.currentTimeMillis() / 1000));
        // 判断是否有更新时间字段，有则更新，没有则新增
        if (metaObject.hasGetter("updateTime")) {
            // metaObject.setValue("updateTime", new Date());
            metaObject.setValue("updateTime", (int) (System.currentTimeMillis() / 1000));
        }
    }

    /**
     * 更新元对象字段填充
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
         // 更新时自动填充 update_time 字段
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.getOriginalObject().toString());
        // metaObject.setValue("updateTime", new Date());
        metaObject.setValue("updateTime", (int) (System.currentTimeMillis() / 1000));
    }
}
